package jbase.project.system.net.http.management;

import java.util.HashMap;
import java.util.Map;

import jbase.project.system.core.Sys;
import jbase.project.system.core.common.EventHook;
import jbase.project.system.core.common.HookEventConstants;
import jbase.project.system.core.defaults.DefaultEventHook;
import jbase.project.system.net.http.HttpEventHandleHook;
import jbase.project.system.net.http.HttpService;
import jbase.project.system.net.http.HttpService.Status;
import jbase.project.system.net.http.IHttpHandle;

public class ManagementServer implements HookEventConstants {

	private String localhost;
	private int port;
	private boolean is_binded = false;
	private EventHook hook;
	private HttpService http;
	private EventHook httpHandleHook;
	Map<String, Object> serverConfig;
	private IHttpHandle handle;

	public ManagementServer(EventHook hook, String localhost, int port, IHttpHandle handle) {
		super();
		this.hook = hook;
		this.handle = handle;
		bind(localhost, port);
	}

	public void bind(String localhost, int port) {
		this.localhost = localhost;
		this.port = port;
		this.is_binded = true;
	}

	public boolean start() {
		if (is_binded) {
			this.serverConfig = new HashMap<>();
			this.httpHandleHook = new HttpEventHandleHook(handle);
			Sys.setVar("management.server.http.hand.hook", this.httpHandleHook);
			Sys.setVar("management.server.console.http.handle", handle);
			this.http = new HttpService(this.httpHandleHook, this.localhost, this.port);
			HttpService.Status status = this.http.activeServer(this.serverConfig);
			this.hook.event(HOOK_EVENT_OUT, this, "success");
			return status == Status.IS_SUCCESS;
		} else {
			return false;
		}
	}

	public static void main(String[] as) {
		JavaScriptConsoleHttpHandle jsConsoleHttpHandle = new JavaScriptConsoleHttpHandle(new DefaultEventHook());
		ManagementServer ms = new ManagementServer(new DefaultEventHook(), "localhost", 8080, jsConsoleHttpHandle);
		if (!ms.start()) {
			System.out.println("--创建服务失败--");
		} else {
			System.out.println("--创建服务成功--");
		}
	}

}
